package com.welson.db.cryptor.wrapper;

import com.baomidou.mybatisplus.core.conditions.update.Update;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.welson.db.cryptor.util.EncryptHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * 支持加密字段的QueryWrapper
 * @author welson
 */
public class EncryptUpdateWrapper<T> extends AbstractEncryptWrapper<T, String, EncryptUpdateWrapper<T>> implements Update<EncryptUpdateWrapper<T>, String> {

    /**
     * SQL 更新字段内容，例如：name='1', age=2
     */
    private final List<String> sqlSet;

    public EncryptUpdateWrapper() {
        super.setEntity(null);
        super.initNeed();
        this.sqlSet = new ArrayList<>();
    }

    @Override
    protected EncryptUpdateWrapper<T> instance() {
        return new EncryptUpdateWrapper<>();
    }


    @Override
    public String getSqlSet() {
        if (CollectionUtils.isEmpty(sqlSet)) {
            return null;
        }
        return String.join(Constants.COMMA, sqlSet);
    }

    public EncryptUpdateWrapper<T> encryptSet(String column, Object val) {
        return encryptSet(true, column, val, null);
    }

    public EncryptUpdateWrapper<T> encryptSet(boolean condition, String column, Object val) {
        return encryptSet(condition, column, val, null);
    }

    public EncryptUpdateWrapper<T> encryptSet(String column, Object val, String mapping) {
        return encryptSet(true, column, val, mapping);
    }

    public EncryptUpdateWrapper<T> encryptSet(boolean condition, String column, Object val, String mapping) {
        return set(condition, column, EncryptHandler.encrypt(val), mapping);
    }

    @Override
    public EncryptUpdateWrapper<T> set(boolean condition, String column, Object val, String mapping) {
        return maybeDo(condition, () -> {
            String sql = formatParam(mapping, val);
            sqlSet.add(column + Constants.EQUALS + sql);
        });
    }

    @Override
    public EncryptUpdateWrapper<T> setSql(boolean condition, String sql) {
        if (condition && StringUtils.isNotBlank(sql)) {
            sqlSet.add(sql);
        }
        return typedThis;
    }

    @Override
    protected String columnSqlInjectFilter(String column) {
        return StringUtils.sqlInjectionReplaceBlank(column);
    }

    /**
     * 返回一个支持 lambda 函数写法的 wrapper
     */
    public EncryptLambdaUpdateWrapper<T> lambda() {
        return new EncryptLambdaUpdateWrapper<>(getEntity(), getEntityClass(), sqlSet, paramNameSeq, paramNameValuePairs,
                expression, paramAlias, lastSql, sqlComment, sqlFirst);
    }

    @Override
    public void clear() {
        super.clear();
        sqlSet.clear();
    }
}